package com.ruoyi.tplus.Interceptor;

/**
 * @Author: zhanglm
 * @CreateDate: 2025-06-19 13:13
 * @FullNameClass: com.ruoyi.kis.Interceptor.MyInterceptor
 * @Description:
 */
import com.alibaba.fastjson.JSONObject;
import com.ruoyi.common.exception.base.BaseException;
import com.ruoyi.tplus.annotaion.BasicAuthCheck;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.util.Base64Utils;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.lang.reflect.Method;
import java.util.Optional;

@Configuration
@Component
public class MyInterceptor implements HandlerInterceptor {


    @Value("${wms.Authorization}")
    private String AUTH_HEADER;

    @Value("${wms.basic-auth}")
    private String BASIC_AUTH;

    /**
     * controller执行前
     * @param request current HTTP request
     * @param response current HTTP response
     * @param obj chosen handler to execute, for type and/or instance evaluation
     * @return true to continue processing the request; false to stop and return the response immediately
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object obj) throws Exception {
        if (!(obj instanceof HandlerMethod)) return true;
        Method method = ((HandlerMethod) obj).getMethod();
        //只有包含该注解的controller才会被拦截
        if (method.isAnnotationPresent(BasicAuthCheck.class)) {
            //请求头是否包含Basic
            Optional<String> tOpt= Optional.ofNullable(request.getHeader(AUTH_HEADER));
            if (!tOpt.isPresent()){
                outError(response,"The request header does not contain Basic");
                return false;
            }
            if (!authVerify(tOpt.get())){
                outError(response,"Basic authentication failure");
                return false;
            }
        }
        return true;
    }

    //校验
    private boolean authVerify(String token){
        if (token == null || token.isEmpty()){
            return false;
        }
        token = token.replace("Basic","").trim();
        //base64解码
        String res = new String(Base64Utils.decode(token.getBytes()));
        return res.equals(BASIC_AUTH);
    }

    //输出异常信息
    private void outError(HttpServletResponse response,String msg) {
        response.setStatus(HttpStatus.UNAUTHORIZED.value());
        response.setContentType("application/json");
        response.setCharacterEncoding("UTF-8");
        JSONObject obj = new JSONObject();
        obj.put("code",HttpStatus.UNAUTHORIZED.value());
        obj.put("message",msg);
//        JSONObject json = new JSONObject();
//        json.put("error",obj);
        try {
            PrintWriter writer = response.getWriter();
            // 将异常信息写入响应输出流
//            writer.println(json);
            writer.println(obj);
        } catch (IOException ex) {
            throw new BaseException("401");
        }
    }

    //控制器方法调用之后，解析式图之前
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
    }

    //controller执行完成后
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
    }
}
